//
//  ZCHomeTableViewController.swift
//  weibo
//
//  Created by Ning Xie on 16/8/8.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

private let HomeTableViewCellIdentifier = "HomeTableViewCellIdentifier"

class ZCHomeTableViewController: ZCVisitorTableViewController {

    
    private lazy var statusListViewModel:ZCStatusListViewModel = ZCStatusListViewModel()
    
    var statusList:[ZCStatusModel]?
    
    
    //上拉加载数据空间
    private lazy var pullupView:UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
        view.color = UIColor.redColor()
        return view
    }()
    
    //下拉刷新数据控件
    private lazy var pulldownView:UIRefreshControl = {
       let view = UIRefreshControl()
        view.addTarget(self, action: #selector(ZCHomeTableViewController.startRefresh), forControlEvents: .ValueChanged)
        return view
    }()
    
    //提示刷新微博数量
    private lazy var tipView: UILabel = {
       let label = UILabel()
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = .Center
        label.textColor = UIColor.whiteColor()
        label.alpha = 0.01
        label.sizeToFit()
        
        return label
    }()
    
    //搜索栏
    private lazy var searchBar:UISearchBar = {
        
       let bar = UISearchBar(frame: CGRectMake(0, 0, 0, 30))
        bar.barTintColor = UIColor.lightGrayColor()
        bar.placeholder = "大家都在搜索王宝强"
        bar.delegate = self
        return bar
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //判断是否登录
        if isLogin {
            setupUI()
            loadData()
        }
       
    }
    
    //滚动到顶端
    @objc private func scrollToTop(){
        
        self.tableView.setContentOffset(CGPointMake(0, -64), animated: true)
    }
    
    
    private func setupUI(){
        setupTableView()
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "回到顶部", target: self, action: #selector(ZCHomeTableViewController.scrollToTop))
        
        view.addSubview(tipView)
        
        tipView.snp_makeConstraints { (make) in
            make.top.equalTo(self.view)
            make.width.equalTo(UIScreen.mainScreen().bounds.size.width)
            make.height.equalTo(30)
        }

    }
    
    //设置tableview的属性
    private func setupTableView(){
        
        tableView.registerClass(ZCStatusTableViewCell.self, forCellReuseIdentifier: HomeTableViewCellIdentifier)
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 200
        tableView.separatorStyle = .None
        tableView.tableHeaderView = searchBar
        tableView.tableFooterView = pullupView
        pullupView.sizeToFit()
        tableView.addSubview(pulldownView)
    }

    //重新加载数据
    private func loadData()
    {
        statusListViewModel.loadData(pullupView.isAnimating()) { (newInfo ,isSuccess) in
        
        if !self.pullupView.isAnimating() && newInfo != "暂无新微博"{
            
            self.startTipViewAnimation(newInfo)
        }
        
        self.stopRefresh()
        if isSuccess
        {
            self.tableView.reloadData()
                
        }else
        {
            print("数据请求异常")
        }
        
        }
    }
    
    private func startTipViewAnimation(newInfo:String){
        
        tipView.text = newInfo
        UIView.animateWithDuration(1.5, animations: {
            self.tipView.alpha = 1
        }) { (_) in
            UIView.animateWithDuration(1.5, animations: {
                self.tipView.alpha = 0
            })
        }

    }
    //开始下拉刷新
    @objc private func startRefresh(){
        
        loadData()
        
    }
    
    //停止动画
    private func stopRefresh(){
        
        pullupView.stopAnimating()
        pulldownView.endRefreshing()
        
    }
    
}


// MARK: - Tableview的数据源代理
extension ZCHomeTableViewController{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.statusList.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeTableViewCellIdentifier, forIndexPath: indexPath) as! ZCStatusTableViewCell
        
        //  给cell绑定数据
        cell.statusViewModel = statusListViewModel.statusList[indexPath.row]
        
        return cell
        
    }

    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == statusListViewModel.statusList.count - 1 && !pullupView.isAnimating(){
            pullupView.startAnimating()
            loadData()
        }
    }
    
    override func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        view.endEditing(true)
    }

}

//MARK: -UISearchBar的代理方法
extension ZCHomeTableViewController:UISearchBarDelegate{
    
    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        view.endEditing(true)
    }
//    func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
//        let searchView = UITableViewController()
//        
//        
//        self.navigationController?.pushViewController(searchView, animated: true)
//        return true
//    }
    
}
